package com.milk.base;

import android.app.Activity;
import android.app.Application.ActivityLifecycleCallbacks;
import android.os.Bundle;

import java.util.ArrayList;
import java.util.List;

public class ActivityLifecycleCallbacksWrapper implements ActivityLifecycleCallbacks {
    private List<ApplicationSwitchMonitor> mApplicationSwitchMonitors = new ArrayList<ApplicationSwitchMonitor>();
    private short switchCount = 0;

    public void addApplicationSwitchMonitor(ApplicationSwitchMonitor monitor) {
        if (null == monitor) return;
        mApplicationSwitchMonitors.add(monitor);
    }

    public void removeApplicationSwitchMonitor(ApplicationSwitchMonitor monitor) {
        if (null == monitor) return;
        mApplicationSwitchMonitors.remove(monitor);
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(Activity activity) {
        if (switchCount <= 0) {
            switchCount = 0; //防止错误，校准下
            for (ApplicationSwitchMonitor callback : mApplicationSwitchMonitors) {
                callback.applicationEnterForeground();
            }
        }
        switchCount++;
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        switchCount--;
        if(switchCount <= 0){
            switchCount = 0;
            for(ApplicationSwitchMonitor callback : mApplicationSwitchMonitors){
                callback.applicationEnterBackground();
            }
        }

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
}
